<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入任务标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="任务描述" prop="description">-->
<!--        <el-input-->
<!--          v-model="queryParams.description"-->
<!--          placeholder="请输入任务描述"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.task_state"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="关联用户" prop="assignedUserId">-->
      <!--        <el-select v-model="queryParams.assignedUserId" placeholder="请选择关联用户" clearable>-->
      <!--          <el-option-->
      <!--            v-for="dict in dict.type.sys_user_sex"-->
      <!--            :key="dict.value"-->
      <!--            :label="dict.label"-->
      <!--            :value="dict.value"-->
      <!--          />-->
      <!--        </el-select>-->
      <!--      </el-form-item>-->
      <el-form-item label="任务开始时间" prop="startDate" label-width="120px">
        <el-date-picker clearable
                        v-model="queryParams.startDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务结束日期" prop="endDate" label-width="120px">
        <el-date-picker clearable
                        v-model="queryParams.endDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['xm:task:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->

      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['xm:task:edit']"-->
      <!--        >修改</el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['xm:task:remove']"-->
      <!--        >删除</el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['xm:task:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="任务标题" align="center" prop="title">
        <template slot-scope="scope">
          <span :class="{ 'red-text': isRed(scope.row) }"
                :title="isRed(scope.row)?'已逾期,请请尽快完成':''">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务描述" align="center" prop="description">
        <template slot-scope="scope">
          <div class="cell-with-ellipsis">{{ scope.row.description }}</div>
        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectName"/>
      <el-table-column label="优先级" align="center" prop="priority"/>

      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.task_state" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="关联用户" align="center" prop="name"/>

      <el-table-column label="开始时间" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="截止日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span :class="{ 'red-text': isRed(scope.row) }" :title="isRed(scope.row)?'已逾期,请请尽快完成':''">{{
              parseTime(scope.row.endDate, '{y}-{m}-{d}')
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="completeTask(scope.row)"
            v-if="scope.row.status !=1"
            v-hasPermi="['xm:task:edit']"
          >查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="acceptanceTask(scope.row)"
            v-if="scope.row.status ==4&&scope.row.createBy==user.userId"
            v-hasPermi="['xm:task:edit']"
          >验收完成
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="completeTask(scope.row)"
            v-if="scope.row.status ==3&&scope.row.assignedUserId==user.userId"
            v-hasPermi="['xm:task:edit']"
          >完成
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="checkTask(scope.row)"

            v-if="scope.row.status ==2&&scope.row.assignedUserId==user.userId"
            v-hasPermi="['xm:task:edit']"
          >查收
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="publish(scope.row)"
            v-if="scope.row.status ===1"
            v-hasPermi="['xm:task:edit']"
          >发布
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status ==1"
            v-hasPermi="['xm:task:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status ==1"
            v-hasPermi="['xm:task:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isModify">
        <el-form-item label="任务标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入任务标题"/>
        </el-form-item>
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入任务描述" resize="none" rows="8"/>
        </el-form-item>
        <el-form-item label="所属项目" prop="projectName">
          <el-select v-model="form.projectName" placeholder="请选择项目" @change="updateProjectName()">
            <el-option
              v-for="dict in projectList"
              :key="dict.id"
              :label="dict.name"
              :value="dict"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联用户" prop="assignedUserId">
          <el-select v-model="form.assignedUserId" placeholder="请选择关联用户">
            <el-option
              v-for="dict in userList"
              :key="dict.userId"
              :label="dict.userName"
              :value="+dict.userId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="优先级" prop="assignedUserId">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option
              v-for="dict in dict.type.priority"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startDate">
          <el-date-picker clearable
                          v-model="form.startDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="截止日期" prop="endDate">
          <el-date-picker clearable
                          v-model="form.endDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择截止日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" resize="none"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
<!--    <el-button type="text" @click="open1">点击打开 Message Box</el-button>-->
  </div>
</template>

<script>
import {listTask, getTask, delTask, addTask, updateTask} from "@/api/xm/task"
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  resetUserPwd,
  changeUserStatus,
  deptTreeSelect
} from "@/api/system/user"
import {listProject, getProject, delProject, addProject, updateProject} from "@/api/xm/project"
import {getUserProfile} from "../../../api/system/user";
let socket;
export default {
  name: "Task",
  dicts: ['sys_user_sex', 'priority', "task_state"],
  data() {
    return {
      dialogFormVisible :false,
      mes:null,
      isModify: true,
      user: {userId: null},
      userList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 任务表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        description: null,
        projectName: null,
        status: null,
        assignedUserId: null,
        startDate: null,
        endDate: null,
      },
      projectList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "任务标题不能为空", trigger: "blur"}
        ],
        description: [
          {required: true, message: "任务描述不能为空", trigger: "blur"}
        ],
        priority: [
          {required: true, message: "优先级不能为空", trigger: "change"}
        ],
        assignedUserId: [
          {required: true, message: "关联用户不能为空", trigger: "change"}
        ],
        startDate: [
          {required: true, message: "开始时间不能为空", trigger: "change"}
        ],
        endDate: [
          {required: true, message: "截止日期不能为空", trigger: "change"}
        ],
        projectName: [
          {required: true, message: "所属项目不能为空", trigger: "blur"}
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getUser()
    this.getListUser()
    this.getListProject()
  },
  methods: {
    open1(data) {
      this.$alert(data, "消息", {
        confirmButtonText: '确定',
        callback: action => {
          this.getList();
        }
      });
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },
    init() {
      let that = this;

      if (typeof (WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {

        let socketUrl = "ws://localhost:8080/socket/"+this.user.userId ;
        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 开启一个websocket服务
        socket = new WebSocket(socketUrl);
        // 连接打开时的回调函数
        socket.onopen = function(event) {
          console.log("WebSocket连接已打开");
          // 可以在这里发送一个初始消息给服务器
          // socket.send("Hello Server!");
        };

// 接收到消息时的回调函数
        socket.onmessage = function(event) {
          console.log("接收到消息: " + event.data);
          // 在这里处理服务器发送的消息

          that.open1(event.data)
        };

// 连接关闭时的回调函数
        socket.onclose = function(event) {
          console.log("WebSocket连接已关闭");
        };

// 连接出错时的回调函数
        socket.onerror = function(error) {
          console.error("WebSocket发生错误: " + error);
        };
      }
    },
    updateProjectName() {
      this.form.projectId = this.form.projectName.id

      this.form.projectName = this.form.projectName.name
    },

    isRed(row) {
      const today = new Date();
      const endDate = new Date(row.endDate);
      return endDate <= today && [2, 3, 4].includes(row.status);
    },

    /** 查询任务列表 */
    getList() {

      this.loading = true
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data
        console.log(this.user, "this.user")
        this.init();
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: null,
        description: null,
        projectName: null,
        priority: null,
        status: null,
        id: null,
        assignedUserId: null,
        startDate: null,
        endDate: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        projectId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getListUser()
      this.getListProject()
      this.open = true
      this.form.status = 1
      this.title = "添加任务"
      this.isModify = false
    },
    acceptanceTask(row) {
      this.reset()
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data
        this.form.status = 5
        this.open = true
        this.title = "验收任务"
        this.isModify = true

      })
    },
    completeTask(row) {
      debugger
      console.log(row.status ==2&&row.assignedUserId==this.user.userId)
      this.reset()
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data
        this.form.status = 4
        this.open = true
        this.title = "完成任务"
        this.isModify = true

      })
    },
    checkTask(row) {
      this.reset()

      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data
        this.form.status = 3
        this.open = true
        this.isModify = true
        this.title = "查看任务"
      })
    },

    publish(row) {
      this.reset()
      this.getListUser()
      this.getListProject()
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data
        this.form.status = 2
        this.open = true
        this.isModify = false
        this.title = "发布任务"
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(this.dict.type.priority)

      this.reset()
      this.getListUser()
      this.getListProject()
      const id = row.id || this.ids
      getTask(id).then(response => {
        this.form = response.data
        console.log(response.data)
        this.form.status = 1
        this.open = true
        this.title = "修改任务"
        this.isModify = false
      })
    },
    /** 提交按钮 */
    submitForm() {

  
    if(this.title=="修改任务"||this.title=="发布任务"||this.title=="添加任务"){
      if (this.form.endDate < this.form.startDate) {
        this.$modal.msgError("结束时间不能早于开始时间")
        return
      }

      const today = new Date();
      const endDate = new Date(this.form.endDate);

      if (endDate <= today) {
        this.$modal.msgError("结束时间不能早于当前日期")
        return
      }

    }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    getListProject() {
      let data = {
        state: 2
      }
      listProject(data).then(response => {
        this.projectList = response.rows
      })
    },
    getListUser() {
      this.loading = true
      let data = {
        status: 0
      }
      listUser(data).then(response => {
          this.userList = response.rows
          this.loading = false
        }
      )
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除任务编号为"' + ids + '"的数据项？').then(function () {
        return delTask(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('xm/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
}

</script>
<style scoped>
.red-text {
  color: red;
}
.cell-with-ellipsis {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出的文本 */
  text-overflow: ellipsis; /* 使用省略号表示溢出的文本 */
}
</style>
